package com.wlj.web.async;

import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.Callable;

@RestController
public class AsyncController {

    @Autowired
    private MockQueue mockQueue;

    //deferred延期的
    @Autowired
    private DeferredResultHolder deferredResultHolder;

    private Logger logger= LoggerFactory.getLogger(getClass());

    //异步处理请求主要为了增加服务器tomcat吞吐量
    @RequestMapping("/order")
    public DeferredResult<String> order() throws InterruptedException {
        logger.info("主线程开始..");

        String orderNum = RandomStringUtils.randomNumeric(8);
        mockQueue.setPlaceOrder(orderNum);

        DeferredResult<String> result = new DeferredResult<>();
        deferredResultHolder.getMap().put(orderNum,result);

        logger.info("主线程返回..");
        //下单服务和处理订单服务完全隔离，不知道彼此的存在
        return result;
    }

    /**
     * 业务逻辑放到副线程中，主线程(tomcat线程没有停顿)很快返回，就可以去接受其他http请求，增加了吞吐量
     * 缺点、不足:副线程需要由主线程调起，在复杂的业务场景中，这不合适
     * @return
     */
    @RequestMapping("/order2")
    public Callable<String> order2(){
        logger.info("主线程开始");
        Callable<String> res = new Callable<String>() {

            @Override
            public String call() throws Exception {
                logger.info("副线程开始");
                Thread.sleep(1000);
                logger.info("副线程返回");
                return "success";
            }
        };
        logger.info("主线程返回");
        return res;
    }
}
